package com.zzyl.interceptor;


import com.zzyl.entity.JwtConstants;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Service
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取header种的token，key：authorization
        String token = request.getHeader(JwtConstants.TOKEN_KEY);
        // 判断token是否为空
        if(StringUtils.isEmpty(token)){
            // 如果token是空， 返回401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        // 如果token不是空
        // 解析token
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getBase64EncodedSecretKey(), token);
            // 如果解析token成功，获取token种的memberId
            Long memberId = claims.get(JwtConstants.MEMBER_ID, Long.class);
            if(memberId == null || memberId <= 0 ){
                response.setStatus(HttpStatus.UNAUTHORIZED);
                return false;
            }else{
                // 把memberId保存到ThreadLocal
                UserThreadLocal.set(memberId);
                log.info("保存用户id到TL：{}", memberId);
                return true;
            }
        }catch(Exception e){
            // 如果解析token失败， 返回401
            log.error(e.getMessage(), e);
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       log.info("postHandle执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行");
    }
}
